package com.yangtao.framework.web.intercepter;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.yangtao.framework.common.Pagination;
import com.yangtao.framework.web.struts2.BaseAction;
import com.yangtao.framework.web.struts2.BaseModel;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;

/**
 * 专门为dojo设计的拦截器<br>
 * 用于将dojo传来的参数封装为分页参数
 *
 * @author 杨涛
 * @version 1.0
 */
public class DojoInterceptor extends AbstractInterceptor {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation action) throws Exception {
		if (action.getAction() instanceof BaseAction<?, ?>) {
			BaseAction<?, ?> ba = (BaseAction<?, ?>) action.getAction();
			BaseModel model = ba.getModel();
			Pagination page = model.getPage();
			HttpServletRequest request = ServletActionContext.getRequest();
			int start = request.getParameter("start") == null ? 0 : str2Int(request.getParameter("start"));
			int count = request.getParameter("count") == null ? 0 : str2Int(request.getParameter("count"));
			page.setStart(start);
			page.setCount(count);
		}
		return action.invoke();
	}

	private int str2Int(String str) {
		int ret = 0;
		try {
			ret = Integer.parseInt(str);
		} catch (NumberFormatException e) {
		}
		return ret;
	}

}
